var util = require('../../utils/util.js');
var app = getApp()
var userNickName = ''

// 服务地址
var gpsUrl = util.getGPSDomain() + '/wxweb/gps'
var gateUrl = util.getGPSDomain() + '/wxweb/weixin'
var startDate = getDate()
var endDate = getDate()
var selectEndDate = getDate()
// 要绘制的线
var drawingLines = []
// 距离较远的点组
var tooFarPointPairs = []
// 地图显示边界
var includePoints = null
// 是否第一次浏览历史数据，用于判断是否刷新地图范围
var isFirstViewHistory = true

// 绿色
var GreenColor = '#2E8B57DD'
// 蓝色
var BlueColor = '#0000FFDD'
// 紫色
var PurpleColor = '#AE00AEDD'
// 黄色
var YellowColor = '#5B5B00DD'

// 用户列表
var userPickerArray = []
var userPickerIndex = 0

var pickerArray = []
pickerArray[0] = '已接单'
pickerArray[1] = '完成'
// pickerArray[2] = '状态C'
var regionCode = null
var regionName = null

Page({
  data: {
    latitude: 0,
    longitude: 0,
    mapStyle: 'width: 100%; height: 95vh;',
    markers: "",
    circles: "",
    polyline: "",
    picStyle: 'width: 0; height: 0; display: none',
    videoStyle: 'width: 0; height: 0; display: none',
    picSrc: "",
    videoSrc: "",
    // 选择用户
    userPickerStyle: 'display: none',
    userPickerIndex: userPickerIndex,
    userPickerArray: userPickerArray,
    // 选择区域值
    pickerStyle: 'display: none',
    pickerIndex: 0,
    pickerArray: pickerArray,
    regionName: regionName,
    controls: '',
    nickName: '',
    includePoints: ''
  },
  bindStartDateChange: function (e) {
    startDate = e.detail.value
    this.setData({
      startDate: startDate
    })
    // 置空地图边界
    includePoints = null
    // console.log("in bindStartDateChange")
    // 如果日期是历史日期，则设置isFirstViewHistory为true
    if (isToday(startDate)) {
      isFirstViewHistory = false
    } else {
      isFirstViewHistory = true
    }
    refreshMap()
    getPic()
  },
  // bindEndDateChange: function (e) {
  //   endDate = e.detail.value
  //   this.setData({
  //     endDate: endDate
  //   })
  //   refreshMap()
  // },
  controltap(e) {
    app.mapPage.setData({ controls: '' })
    //   if (e.controlId == 1) {
    //     var coord = app.coord
    //     var lon = coord.split(",")[0];
    //     var lat = coord.split(",")[1];
    //     // 必须先设置到parseInt后的地方，再设置到lon才生效
    //     this.setData({ longitude: parseInt(lon), latitude: parseInt(lat) })
    //     this.setData({ longitude: lon, latitude: lat })
    //   }
  },
  markertap(e) {
    // console.log(e.markerId)
    var contentUrl = null;
    var contentType = 'pic'
    for (var i = 0; i < markers.length; i++) {
      if (markers[i] != null) {
        var id = markers[i].id;
        if (id == e.markerId) {
          contentUrl = markers[i].contentUrl;
          contentType = markers[i].contentType;
        }
      }
    }
    if (contentUrl != null) {
      if (contentType == 'video') {
        // 显示视频
        app.mapPage.setData({ picStyle: 'height: 0; display: none', videoStyle: 'height: 200px', videoSrc: contentUrl })
      } else {
        // 显示图片
        app.mapPage.setData({ videoStyle: 'height: 0; display: none', picStyle: 'height: 200px', picSrc: contentUrl })
      }
    }
  },
  maptap(e) {
    // 隐藏图片和视频
    app.mapPage.setData({ videoStyle: 'height: 0; display: none', picStyle: 'height: 0; display: none' })
  },
  bindUserPickerChange(e) {
    var index = e.detail.value
    var userInfo = app.userInfos[index]
    if (userInfo.name) {
      userNickName = userInfo.name
      refreshMap()
      // 选择值改变
      this.setData({
        userPickerIndex: index
      })
    }
  },
  bindPickerChange(e) {
    // 选择值改变
    this.setData({
      pickerIndex: e.detail.value
    })
  },
  onLoad: function (e) {
    isFirstViewHistory = true
    // 读取URL的参数
    //console.log("[map]e.userType:" + e.userType)
    app.mapPage = this

    // 动态设置map的宽和高
    wx.getSystemInfo({
      success: function (res) {
        // app.mapPage.setData({
        //   controls: [{
        //     id: 1,
        //     iconPath: '/resources/pos.png',
        //     position: {
        //       left: 20,
        //       top: res.windowHeight - 100,
        //       width: 30,
        //       height: 30
        //     },
        //     clickable: true
        //   }]
        // })
      }
    })

    var date = getDate()
    userNickName = app.nickName
    this.setData({ startDate: date, nickName: userNickName })
    //this.setData({ selectStartDate: date }), endDate: date, selectEndDate: date
    // 刷新地图
    refreshMap()
    // 定时刷新地图
    var timer = setInterval(refreshMap, 30 * 1000)
    // 获取图片
    getPic()
    // 显示用户列表
    showUsers()
  }
})

// function controltap(e) {
//     console.log(e.controlId)
//     if (e.controlId == 1) {
//       var coord = app.coord
//       var x = coord.split(",")[0];
//       var y = coord.split(",")[1];
//       this.setData({
//         latitude: y,
//         longitude: x
//       })
//     }
//   }

var points = new Array()
// 第0个是当前位置图标；后面的是照片图标
var markers = new Array()
// 定时刷新地图
function refreshMap() {
  var coord = app.coord
  if (app.coord != "0,0") {
    var lon = coord.split(",")[0];
    var lat = coord.split(",")[1];
    //console.log("coord:" + lon + "," + lat)
    // console.log("userNickName=" + userNickName + ", app.nickName=" + app.nickName)
    if (app.nickName == userNickName) {
      var marker = new Object()
      marker.id = 0;
      // 转换为数字类型，否则iOS上运行有问题
      lon = parseFloat(lon)
      lat = parseFloat(lat)
      marker.longitude = lon
      marker.latitude = lat
      marker.name = app.nickName
      // 只更新第一个marker，即当前位置
      markers[0] = marker
      if (isFirstViewHistory) {
        app.mapPage.setData({ longitude: lon, latitude: lat, markers: markers })
      } else {
        app.mapPage.setData({ markers: markers })
      }
    } else {
      // 只更新第一个marker，即当前位置
      markers[0] = null
      // 如果选择的用户不是自己，就不显示自己的坐标
      app.mapPage.setData({ markers: markers })
    }

    // console.log("startDate:" + startDate)
    // 查询GPS数据
    wx.request({
      url: gpsUrl,
      data: {
        a: userNickName,
        start: startDate.replace("-", "").replace("-", ""),
        end: startDate.replace("-", "").replace("-", "")
        // end: endDate.replace("-", "").replace("-", "")
      },
      // header: {
      //   'content-type': 'application/json'
      // },
      success: function (res) {
        //console.log("res.data:" + res.data)
        var lines
        if (res.data.indexOf("^^") != -1) {
          lines = res.data.split("^^")
        } else {
          lines = new Array()
          if (res.data != "NoData") {
            lines[0] = res.data
          } else {
            //console.log("res.data=" + res.data)
          }
        }
        var gpsPoints = new Array()
        // 距离较远的点组
        tooFarPointPairs = []
        for (var i = 0; i < lines.length; i++) {
          var line = lines[i]
          //console.log("line:" + line)
          var gpsDate = line.split("^")[0]
          var points = line.split("^")[1]
          if (points) {
            points = points.split("__")
            var lastGpsPoint = null;
            try {
              for (var j = 0; j < points.length; j++) {
                var point = points[j]
                var arr = point.split(",")
                var accuracy = arr[14]
                var deleteTag = arr[16]
                // if (accuracy > 0) {
                if (deleteTag == "" || deleteTag == "null" || deleteTag == "0") {
                  var gpsPoint = new Object()
                  gpsPoint.gpsDataTime = arr[3]
                  var lon = arr[7]
                  var lat = arr[8]
                  // 转换为数字类型，否则iOS上运行有问题
                  // try catch似乎无效
                  // try {
                  if (typeof (lon) == "string") {
                    lon = parseFloat(lon)
                    lat = parseFloat(lat)
                  } else {
                    // util.logToServer(userNickName, 'typeof lon is not string')
                  }
                  // } catch (ep) {
                  //   util.logToServer(userNickName, 'parseFloat err')
                  // }
                  gpsPoint.longitude = lon
                  gpsPoint.latitude = lat
                  var speed = 0
                  var distance = 0
                  if (lastGpsPoint != null) {
                    var gpsDataTime = new Date(gpsPoint.gpsDataTime)
                    var lastGpsDataTime = new Date(lastGpsPoint.gpsDataTime)
                    // 小时
                    var deltaTime = (gpsDataTime.getTime() - lastGpsDataTime.getTime()) / 1000 / 3600;
                    //console.log("deltaTime:" + deltaTime)
                    var deltaX = gpsPoint.longitude - lastGpsPoint.longitude;
                    //console.log("deltaX:" + distance)
                    var deltaY = gpsPoint.latitude - lastGpsPoint.latitude;
                    //console.log("deltaY:" + deltaY)
                    distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2))
                    // 经纬度转换为公里
                    distance = distance / 0.008983152841196329
                    if (deltaTime > 0) {
                      speed = distance / deltaTime
                    } else {
                      // 时间差非法
                      // util.logToServer(userNickName, '时间差非法,deltaTime=' + deltaTime)
                    }
                  }
                  //console.log("speed:" + speed)
                  // 跳跃距离在3公里内的，才根据超速限制过滤
                  if (distance > 3 || speed < 125) {
                    // var gpsDataTime = new Date(gpsPoint.gpsDataTime)
                    // var testTime = new Date("2017/02/11 15:00:00")
                    // if(gpsDataTime.getTime() < testTime.getTime()){
                    gpsPoints[gpsPoints.length] = gpsPoint

                    if (distance > 2.2) {
                      // 记录距离大于2.2公里的
                      var tooFarPointPair = new Object()
                      tooFarPointPair.startPoint = lastGpsPoint.latitude + "," + lastGpsPoint.longitude
                      tooFarPointPair.endPoint = gpsPoint.latitude + "," + gpsPoint.longitude
                      tooFarPointPair.distance = distance
                      tooFarPointPairs.push(tooFarPointPair)
                    }

                    // 更新lastGpsPoint
                    lastGpsPoint = gpsPoint;
                    // }
                  } else {
                    console.log("speed:" + speed + ",distance:" + distance)
                  }
                } else {
                  console.log("deleteTag:" + deleteTag)
                }
              }
            } catch (err) {
              util.logToServer(userNickName, 'err')
            }
          } else {
            console.log("points is undefined. res.data=" + res.data)
          }
        }
        var line = new Object()
        line.points = gpsPoints
        line.color = BlueColor
        line.width = 3
        line.dottedLine = false
        line.arrowLine = true
        // 清空drawingLines
        drawingLines = []
        // 第0个元素是查询到的轨迹
        drawingLines[0] = line
        if (includePoints == null) {
          includePoints = gpsPoints
          if (isToday(startDate)) {
            // 查看当天轨迹时，刷新地图显示范围
            app.mapPage.setData({ polyline: drawingLines, includePoints: gpsPoints })
          } else {
            // 查看历史轨迹时，仅在第一次刷新地图显示范围
            if (isFirstViewHistory) {
              isFirstViewHistory = false
              app.mapPage.setData({ polyline: drawingLines, includePoints: gpsPoints })
            } else {
              app.mapPage.setData({ polyline: drawingLines })
            }
          }
        } else {
          // 地图显示边界只设置一次
          app.mapPage.setData({ polyline: drawingLines })
        }

        // 距离大于2.2公里的进行道路补全
        // console.log('tooFarPointPairs.length=' + tooFarPointPairs.length)
        for (var i = 0; i < tooFarPointPairs.length; i++) {
          var tooFarPointPair = tooFarPointPairs[i]
          getPath(tooFarPointPair.startPoint, tooFarPointPair.endPoint)
        }

        if (app.rights && app.rights.indexOf('[1]') != -1) {
          // 获取工作区
          getWorkAreas()
        }
      },
      fail: function (res) {
        var msg = "查询GPS数据失败:" + res.data
        console.log(msg);
        util.logToServer(userNickName, msg)
      }
    });
  }
}

function getDate() {
  var date = new Date();
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }

  return year + "-" + month + "-" + day;
}

function isToday(date) {
  return getDate() == date;
}

function getPic() {
  var picUrl = util.getGPSDomain() + '/wxweb/getimage'
  // 获取图片
  wx.request({
    url: picUrl,
    data: {
      user: userNickName,
      day: startDate
    },
    success: function (res) {
      // console.log("getPic success:" + res.data)
      if (app.nickName == userNickName) {
        // 选择的是当前用户才显示当前坐标
        if (markers.length > 1) {
          // 只保留第一个marker，即当前坐标
          var marker = markers[0]
          markers = []
          markers.push(marker)
        }
      } else {
        markers = []
      }
      for (var i = 0; i < res.data.length; i++) {
        var item = res.data[i]
        var coord = item.coord
        var time = item.time
        var contentType = item.contentType
        var name = item.imgNames
        var dirName = "pic"
        var postfix = ".png"
        var title = "(照片)"
        var picIconName = 'marker.png'
        if (contentType == 'video') {
          name = item.videoNames
          dirName = "video"
          postfix = ".mp4"
          title = "(视频)"
          picIconName = 'video.png'
        }
        var x = coord.split(",")[0]
        var y = coord.split(",")[1]
        // 转换为数字类型，否则iOS上运行有问题
        x = parseFloat(x)
        y = parseFloat(y)
        var marker = new Object()
        marker.id = i + 1
        marker.contentType = contentType
        marker.longitude = x
        marker.latitude = y
        marker.name = title + "时间: " + time
        //marker.alpha = 0.5
        // iconPath要用本地路径
        marker.iconPath = '/resources/' + picIconName
        // 点击后要显示的内容的URL
        var contentUrl = util.getGPSDomain() + "/wxweb/" + dirName + "/" + name + postfix
        // console.log(contentUrl)
        marker.contentUrl = contentUrl
        markers.push(marker)
      }
      // console.log("markers.length=" + markers.length)
      app.mapPage.setData({ markers: markers })
    },
    fail: function (error) {
      var msg = "获取图片失败:" + error
      console.log(msg)
      util.logToServer(userNickName, msg)
    }
  })
}

var qqDirectionUrl = 'https://apis.map.qq.com/ws/direction/v1/driving/'
var cachedPaths = []
// startPoint: 39.915285,116.403857
function getPath(startPoint, endPoint) {
  // 暂时不用缓存，因为使用后有问题。怀疑是route被垃圾回收了。
  cachedPaths = []
  // 检查是否有缓存
  var points = null;
  for (var i = 0; i < cachedPaths.length; i++) {
    if (startPoint == cachedPaths[i].startPoint && endPoint == cachedPaths[i].endPoint) {
      points = cachedPaths[i].points
    }
  }
  if (points != null) {
    drawRoute(points, PurpleColor)
  } else {
    // 获取路线
    wx.request({
      url: qqDirectionUrl,
      data: {
        from: startPoint,
        to: endPoint,
        key: 'XKGBZ-ZWY2J-ARQFP-FPGU6-HCCC2-T3BZM'
      },
      success: function (res) {
        // console.log('getPath success. status=' + res.data.status)
        if (res.data && (res.data.status == 0)) {
          var routes = res.data.result.routes
          if (routes.length > 0) {
            // 只有1条路线
            var polyline = routes[0].polyline
            // 解密
            for (var i = 2; i < polyline.length; i++) {
              polyline[i] = polyline[i - 2] + polyline[i] / 1000000
            }
            var points = []
            for (var i = 0; i < polyline.length - 1; i += 2) {
              var y = polyline[i]
              var x = polyline[i + 1]
              var p = new Object()
              p.longitude = x
              p.latitude = y
              points.push(p)
            }
            // 绘制道路
            drawRoute(points, PurpleColor)
            // 缓存
            var cachedPath = new Object()
            cachedPath.startPoint = startPoint
            cachedPath.endPoint = endPoint
            cachedPath.points = points
            cachedPaths.push(cachedPath)
          }
        } else {
          if (res.data) {
            console.log('getPath message=' + res.data.message)
          }
        }
      },
      fail: function (error) {
        console.log('getPath fail')
      }
    })
  }
}

// 绘制道路
function drawRoute(points, color) {
  var line = new Object()
  line.points = points
  line.color = color
  line.width = 3
  line.dottedLine = true
  line.arrowLine = true
  drawingLines.push(line)
  // console.log('drawingLines.length=' + drawingLines.length)
  app.mapPage.setData({ polyline: drawingLines })
}

// 查询工作区
function getWorkAreas() {
  console.log('getWorkAreas.userNickName=' + userNickName)
  wx.request({
    url: gateUrl,
    data: {
      a: userNickName,
      cmd: 'getareas',
      coord: app.coord
    },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      console.log('getWorkAreas success. data=' + res.data)
      if (res.data && res.data.success) {
        var records = res.data.result.records
        if (records.length > 0) {
          // 是否有区域包含当前位置
          var isAnyContain = false
          for (var i = 0; i < records.length; i++) {
            var record = records[i]
            var point2Ds = record.point2Ds
            // console.log('point2Ds.length=' + point2Ds.length)
            var points = []
            for (var j = 0; j < point2Ds.length; j++) {
              var point2D = point2Ds[j]
              var x = point2D.x
              var y = point2D.y
              var point = new Object()
              point.longitude = x
              point.latitude = y
              points.push(point)
            }
            var isContain = record.isContain
            // console.log('isContain=' + isContain)
            if (isContain) {
              isAnyContain = true
              var regionCode = record.region_code
              regionName = record.region_name
              console.log('regionCode=' + regionCode)
              console.log('regionName=' + regionName)
              drawRoute(points, GreenColor)
            } else {
              drawRoute(points, GreenColor)
            }
          }
          if (isAnyContain) {
            // 减小地图高度
            app.mapPage.setData({ pickerStyle: '', regionName: regionName, mapStyle: 'width: 100%; height: 90vh;' })
          } else {
            app.mapPage.setData({ pickerStyle: 'display:none', regionName: '', mapStyle: 'width: 100%; height: 95vh;' })
          }
        }
      }
    },
    fail: function (error) {
      console.log('getWorkAreas fail')
    }
  })
}

// 显示用户列表
function showUsers() {
  userPickerArray = []
  userPickerIndex = 0
  if ((app.role == 'manager' || app.role == 'admin') && (app.userInfos != null)) {
    var found = false
    for (var i = 0; i < app.userInfos.length; i++) {
      var userInfo = app.userInfos[i]
      userPickerArray.push(userInfo.name)
      if (userInfo.name == app.nickName) {
        userPickerIndex = i
        found = true
        break
      }
    }
    if (!found) {
      // 对于管理者，如果列表里没有自己，就加到列表最后
      userPickerArray.push(app.nickName)
      userPickerIndex = userPickerArray.length - 1
    }
    console.log('userPickerIndex = ' + userPickerIndex)
    app.mapPage.setData({ userPickerStyle: '', userPickerArray: userPickerArray, userPickerIndex: userPickerIndex, mapStyle: 'width: 100%; height: 90vh;' })
  } else {
    app.mapPage.setData({ userPickerStyle: 'display:none', userPickerArray: '', userPickerIndex: userPickerIndex, mapStyle: 'width: 100%; height: 95vh;' })
  }
}